package com.example.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.exception.CustomException;
import com.example.service.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//JWT拦截器
@Component
public class JWTInterceptor implements HandlerInterceptor {

    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从http请求里面拿到token
        String token= request.getHeader(Constants.TOKEN);
        if(ObjectUtil.isNull(token)){
            //如果没拿到，再从请求参数里面拿一次
            request.getParameter(Constants.TOKEN);
        }
        //2.开始执行认证
        if(ObjectUtil.isNull(token)){
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        //解析token
        Account account=null;
        try {
            String audience= JWT.decode(token).getAudience().get(0);
            String userid=audience.split("-")[0];
            String role=audience.split("-")[1];
            System.out.println(userid+" "+role);
            //根据用户角色判断属于哪个表，然后查询数据
            if(RoleEnum.ADMIN.name().equals(role)){
                System.out.println("----------------------------");
                account=adminService.selectById(Integer.valueOf(userid));
                System.out.println(account);
            }
        }catch (Exception e){
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        if(ObjectUtil.isNull(account)){
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }

        //通过用户密码作为密钥再次验证token的合法性
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(account.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (Exception e){
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }

        return true;
    }
}
